import axios from 'axios';
import {UserDidSignoutedNotification} from '../base/constants';
import TokenStorage from './TokenStorage';
import {DeviceEventEmitter} from 'react-native';

const getBaseUrl = () => {
    if (__DEV__) {
        return 'https://www.noodlebox.ie/api/v1';
    } else {
        return 'https://www.noodlebox.ie/api/v1';
    }
};

// create an axios instance
const ApiService = axios.create({
    baseURL: getBaseUrl(), // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 0, // request timeout
});

// request interceptor
ApiService.interceptors.request.use(
    async config => {
        // console.log(config);
        // do something before request is sent
        let token = await TokenStorage.getToken();
        if (token) {
            config.headers.Authorization = 'Bearer ' + token;
        }
        config.headers['x-noodlebox-client-id'] = 'Fm8cF4Nm4yRTF22G';
        config.headers['x-noodlebox-client-secret'] = 'oNYT2i1F2MwQH5r1eY6fF6vUqmXLF7CllA8OjiJnH2gFbbUFbIzRHqinqK7Q9SIs';
        return config;
    },
    error => {
        // do something with request error
        console.log('Request Error:', error); // for debug
        return Promise.reject(error);
    },
);

// response interceptor
ApiService.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data;
        //console.log(res);

        // if the custom code is not 20000, it is judged as an error.
        if (res.code) {
            if (res.code === 401) {
                DeviceEventEmitter.emit(UserDidSignoutedNotification);
            }
            return Promise.reject(new Error(res.message || 'Error'));
        } else {
            return res;
        }
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    DeviceEventEmitter.emit(UserDidSignoutedNotification);
                    break;
                default:
                    break;
            }

            console.log('url:', error.request.responseURL); // for debug
            console.log('err:', error.response.data); // for debug
            return Promise.reject(error.response.data);
        } else {
            return Promise.reject(error);
        }
    },
);

export default ApiService;
